<?php

namespace DebugComponent;

/**
 * Builder class
 * Helps to build debug object and set appropriate theme skins
 *
 * @author Milan Hradil
 */
abstract class Builder {

    /**
     * Build debug object
     *
     * @param array $plugins instances of plugins which will be added to debug object
     * @param string $themeDir
     * @return Debug
     */
    public static function build(array $plugins, $themeDir) {
        if (class_exists('\DebugComponent\Plugin\Time') && Plugin\Time::getStartTime() === null) {
            Plugin\Time::setStartTime(\microtime(true));
        }
        if (!\file_exists($themeDir . '/theme.ini')) {
            throw new \RuntimeException('Missing theme.ini file');
        }

        $themeInfo = \parse_ini_file($themeDir . '/theme.ini');
        if (!isset($themeInfo['extension'])) {
            throw new \RuntimeException('Missing extension parameter in theme.ini');
        }
        if (!isset($themeInfo['renderer'])) {
            throw new \RuntimeException('Missing renderer parameter in theme.ini');
        }

        $renderer = new $themeInfo['renderer']();
        if ($renderer instanceof ITemplateRenderer) {
            $renderer->setTemplate($themeDir . '/main.' . $themeInfo['extension']);
        }
        $debug = new Debug($renderer);
        foreach ($plugins as $plugin) {
            if (!$plugin instanceof IPlugin) {
                throw new \RuntimeException('Plugin must implements IPlugin interface');
            }
            if ($plugin instanceof IRenderable) {
                $renderer = new $themeInfo['renderer']();
                if ($renderer instanceof ITemplateRenderer) {
                    $parts = explode('\\', get_class($plugin));
                    $template = preg_replace('/([a-z])([A-Z])/', '\1_\2', array_pop($parts));
                    $template = strtolower($template);
                    $renderer->setTemplate($themeDir . '/' . $template . '.' . $themeInfo['extension']);
                }
                $plugin->setRenderer($renderer);                
            }
            $debug->addPlugin($plugin);
        }
        return $debug;
    }
}